package strategy;

import windows.MainWindow;

public class Vigenere implements AlgorithmInteface {

	private String result;
	private String key;
	private String text;
	private MainWindow ref;
	
	public Vigenere(String text, String key, MainWindow reference) {
		this.text = text;
		this.key = key;
		ref = reference;
	}
	
	@Override
	public void decrypt() {
		int x = 0, len = text.length(), asciiValue, newValue, letterValue;
        String plaintext = new String();
        char current;
        text = text.toLowerCase();//it makes it easier to have it all in one case
        key = key.toLowerCase();
        for (int i = 0; i < len; i++)
        {
            current = text.charAt(i);
            if (current == ' ')
                plaintext += ' ';

            else
            {
                asciiValue = ((int)current);
                if (asciiValue >= 97 && asciiValue <= 122)//if it's a lowercase letter, process it
                {
                    letterValue = asciiValue - 97;
                    newValue = letterValue - (((int)key.charAt(x%key.length())) - 97); //take off the shift
                    newValue %= 26;
                    //if we've gone below 0, we add 26, which has the effect of wrapping around to the end of the alphabet
                    if (newValue < 0)
                        newValue += 26;
                    plaintext += (char)(newValue + 97);//add it to the plaintext
                    x++;
                }
            }
        }
        result = plaintext;
		update();
	}

	@Override
	public void encrypt() {
		int len = text.length(), asciiValue, newValue, letterValue, x = 0;
        String ciphertext = new String();
        char current;
        text = text.toUpperCase(); //it makes it easier to have it all in one case
        key = key.toUpperCase();
        for (int i = 0; i < len; i++)
        {
            current = text.charAt(i);
            if (current == ' ')
                ciphertext += ' ';
            else
            {
                asciiValue = ((int)current);
                //if it's an uppercase letter, encode it
                if (asciiValue >= 65 && asciiValue <= 90)
                {
                    letterValue = asciiValue - 65;
                    newValue = letterValue + (((int)(key.charAt(x%(key.length())))) - 65);//add the shift

                    newValue %= 26;
                    ciphertext += (char)(newValue + 65);//add it to the ciphertext
                    x++;
                }
            }
        }
        result = ciphertext;
        update();
	}

	@Override
	public void autoDecrypt() {

//        update();
	}

	@Override
	public void update() {
		ref.vigenereUpdate(result);
		
	}

}
